package net.k3rnel.abugadro.gcodes;

import net.k3rnel.abugadro.R;
import net.k3rnel.abugadro.gcodes.Comment.Comments;
import net.k3rnel.abugadro.gcodes.Issue.Issues;
import net.k3rnel.abugadro.providers.ProjectsDB;
import net.k3rnel.abugadro.providers.Project.Projects;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler;
import net.k3rnel.abugadro.util.UIUtils;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class BrowseIssue extends ListActivity implements AsyncQueryListener{

	public static final String TAG = "BrowseIssue";

	private CommentsAdapter mAdapter;
	private NotifyingAsyncQueryHandler mHandler;
	private volatile SyncThread mSyncThread;
	private boolean mSync = false;
	private int projId;
	private int issueId;
	private String projName;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gcode_issues_browse);

		final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
		((TextView) findViewById(R.id.title_text)).setText(
				customTitle != null ? customTitle : getTitle());
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		final Uri issuesUri = getIntent().getData();
		projName = getIntent().getStringExtra("projName");
		projId = Integer.parseInt(issuesUri.getPathSegments().get(1));
		issueId = Integer.parseInt(issuesUri.getPathSegments().get(3));

		//		getListView().addHeaderView(findViewById(R.layout.list_issue_contents));
		final ListView listView = getListView();
        final View view = getLayoutInflater().inflate(R.layout.list_issue_contents,
                listView, false);
        listView.addHeaderView(view, null, true);
		mAdapter = new CommentsAdapter(this);
		setListAdapter(mAdapter);

		final Uri commentsUri = Comments.buildUri(issuesUri.getPathSegments().get(1),issuesUri.getPathSegments().get(3));
		Log.i("Abugadro",commentsUri+"");
		mHandler.startQuery(1,null,issuesUri, IssuesQuery.PROJECTION,null,null,null);
		mHandler.startQuery(2,null,commentsUri, CommentsQuery.PROJECTION,Comments.PROJECT_ID + " = " + commentsUri.getPathSegments().get(1)+ 
				" AND "+Comments.ISSUE_ID +" = "+commentsUri.getPathSegments().get(3),null,null);
		startThread();

	}

	public synchronized void startThread(){
		if(mSyncThread == null){
			mSyncThread = new SyncThread(handler);
			mSyncThread.start();
		}
	}
	public synchronized void stopThread(){
		if(mSyncThread != null){
			Thread moribund = mSyncThread;
			mSyncThread = null;
			moribund.interrupt();
		}
	}


	@Override
	public boolean moveTaskToBack(boolean nonRoot) {
		stopThread();
		return super.moveTaskToBack(nonRoot);
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			updateRefreshStatus();
			final Uri projectUri = getIntent().getData();
			final Uri commentsUri = Comments.buildUri(projectUri.getPathSegments().get(1),projectUri.getPathSegments().get(3));
			mHandler.startQuery(2,null,commentsUri, CommentsQuery.PROJECTION,Comments.PROJECT_ID + " = " + commentsUri.getPathSegments().get(1)+ 
					" AND "+Comments.ISSUE_ID +" = "+commentsUri.getPathSegments().get(3),null,null);
		}
	};
	private void updateRefreshStatus() {
		findViewById(R.id.gcode_home_btn_refresh).setVisibility(
				mSync ? View.GONE : View.VISIBLE);
		findViewById(R.id.gcode_home_btn_refresh_progress).setVisibility(
				mSync ? View.VISIBLE : View.GONE);
	}
	/** {@inheritDoc} */
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch(token){
		case 1:
			try {
				if (!cursor.moveToFirst()) return;
				((TextView) findViewById(R.id.gcode_title_entry)).setText(cursor.getString(IssuesQuery.ISSUE_ID)+" - "+ cursor.getString(IssuesQuery.TITLE));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_stars_entry)), "<b>"+cursor.getString(IssuesQuery.STARS)+" Stars</b>");
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_author_entry)),"<b>Reported by </b>"+ cursor.getString(IssuesQuery.AUTHOR));
				final TextView content = ((TextView) findViewById(R.id.gcode_summary_entry));
				content.setText(cursor.getString(IssuesQuery.CONTENT));
				UIUtils.setTextMaybeHtml(content, cursor.getString(IssuesQuery.CONTENT));
				Linkify.addLinks(content, Linkify.WEB_URLS);
				final String owner = cursor.getString(IssuesQuery.OWNER)+"";
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_owner_entry)), "<b>Owner:</b> " + (owner.equals("null") ? "---" : owner));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_status_entry)), "<b>Status:</b> " + cursor.getString(IssuesQuery.STATUS));
				String labels = "";
				labels = ProjectsDB.getInstance().getLabelsByIssueId(getContentResolver(),projId,cursor.getInt(IssuesQuery.ISSUE_ID));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_labels_entry)), "<b>Labels:</b> " + labels);
			}catch(Exception e){
				Log.e("Abugadro","GAH!",e);
			} finally {
				if(cursor!=null)
					cursor.close();
			}
			break;
		case 2:
			startManagingCursor(cursor);
			mAdapter.changeCursor(cursor);
			break;
		}
	}

	/** Handle "home" title-bar action. */
	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}
	/** Handle "refresh" title-bar action. */
	public void onRefreshClick(View v) {
		if(!mSync){
			startThread();
		}
	}
	/** {@link Projects} query parameters. */
	private interface IssuesQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Issues.ISSUE_ID,
				Issues.TITLE,
				Issues.CONTENT,
				Issues.AUTHOR,
				Issues.OWNER,
				Issues.STATUS,
				Issues.STARS,

		};
		//		int ID = 0;
		int ISSUE_ID = 1;
		int TITLE = 2;
		int CONTENT = 3;
		int AUTHOR = 4;
		int OWNER = 5;
		int STATUS = 6;
		int STARS = 7;
	}

	/**
	 * {@link CommentsAdapter} that renders a {@link CommentsQuery}.
	 */
	private class CommentsAdapter extends CursorAdapter {
		private LayoutInflater mInflater;

		public CommentsAdapter(Context context) {
			super(context, null);
			mInflater = LayoutInflater.from(context);
		}

		/** {@inheritDoc} */
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			//			getListView().addHeaderView(findViewById(R.layout.list_issue_contents));
			return getLayoutInflater().inflate(R.layout.list_item_comment, parent, false);
		}

		/** {@inheritDoc} */
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewHolder holder;
			if(view==null){
				view = mInflater.inflate(R.layout.list_item_comment, null);
				holder = new ViewHolder();
				holder.title = (TextView) view.findViewById(R.id.issue_title);
				holder.stuff = (TextView) view.findViewById(R.id.issue_stuff);

				view.setTag(holder);
			}else{
				holder = (ViewHolder) view.getTag();
			}

			holder.title.setText("#"+cursor.getString(CommentsQuery.COMMENT_ID)+" by "+cursor
					.getString(CommentsQuery.AUTHOR));   
			holder.stuff.setText(cursor.getString(CommentsQuery.CONTENT));
			Linkify.addLinks(holder.stuff,Linkify.WEB_URLS);
		}


		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if(convertView==null){
				convertView = mInflater.inflate(R.layout.list_item_comment, parent,false);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.issue_title);
				holder.stuff = (TextView) convertView.findViewById(R.id.issue_stuff);

				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			return super.getView(position, convertView, parent);
		}

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}


	}
	static class ViewHolder {
		TextView title;
		TextView stuff;
	}

	/** {@link Comments} query parameters. */
	private interface CommentsQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Comments.COMMENT_ID,
				Comments.AUTHOR,
				Comments.TITLE,
				Comments.CONTENT,
				Comments.PUBLISHED,


		};
		int COMMENT_ID = 1;
		int AUTHOR = 2;
//		int TITLE = 3;
		int CONTENT = 4;
//		int PUBLISHED = 5;
	}
	public class SyncThread extends Thread {
		Handler mHandler;

		SyncThread(Handler h) {
			mHandler = h;
		}

		public void run() {  
				mSync = true;
				mHandler.sendMessage(new Message());
				try{
					Log.i("Abugadro","Starting parser...");
					new SaxFeedParser(getContentResolver(),"http://code.google.com/feeds/issues/p/"+projName+"/issues/"+issueId+"/comments/full",projId,issueId,1).parse();
				}catch(Exception e){
					//Silently 'do nothing'
					//Mabe change the Sync Icon into a ! to silently alert user what he knows: He has no internet
				}
				mSync = false;
				mHandler.sendMessage(new Message());
				stopThread();
		}	
	}
}